<template>
  <div class="import_param" v-if="dialogVisible">
    <el-dialog
      title="导入参数记录表"
      :visible.sync="dialogVisible"
      width="600px"
      customClass="mes_dialog import_param"
      v-dialogDrag
      :close-on-click-modal="false"
      :before-close="handleClose">
      <div class="step_one mes_file_secret" v-if="step === 1">
        <div class="import_item">
          <div class="import_label"><span class="import_required">*</span>文档密级：</div>
          <div class=" import_cont">
            <el-select v-model="secrecyGrade" size="small" placeholder="请选择密级">
              <el-option
                v-for="item in fileSecretLevel"
                :key="item.id"
                :label="item.label"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="import_item">
          <div class="import_label"><span class="import_required">*</span>选择文件：</div>
          <div class="import_cont">
            <el-upload
              ref="upload"
              class="file_list_cont"
              action=""
              multiple
              :accept="acceptFiles.toString()"
              :limit="10"
              :auto-upload="false"
              :http-request="uploadFile"
              :on-exceed="handleExceed"
              :on-remove="removeFile"
              :on-change="fileChange"
              :file-list="fileList">
              <div class="mes_btn">
                <el-button size="small" class="file_btn">
                  <i class="iconfont icon-btn_addnew" style="color:#00b4ff"></i>
                  选择文件
                </el-button>
                <span class="accept_text" @click.stop="">支持{{acceptFiles.join('、')}}格式</span>
              </div>
            </el-upload>
          </div>
        </div>
      </div>
      <div class="step_two" v-if="step === 2">
        <div>
          <p v-loading="true" style="height: 50px;"></p>
          <p style="width: 100%; text-align: center;">文件上传中</p>
        </div>
      </div>
      <div class="step_three" v-else-if="step === 3">
        <div class="center_msg">
          <i class="iconfont icon-tishi"></i>
          <span>文件上传失败，请重新上传</span>
        </div>
      </div>
      <div class="step_four" v-else-if="step === 4">
        <div>
          <p v-loading="true" style="height: 50px;"></p>
          <p style="width: 100%; text-align: center;">文件解析中</p>
        </div>
      </div>
      <div class="step_five" v-else-if="step === 5">
        <div class="center_msg">
          <i class="iconfont icon-tishi"></i>
          <span>文件解析失败，请重新解析</span>
        </div>
      </div>
      <div class="step_six" v-else-if="step === 6">
        <div class="import_err" v-if="importErrList.length">
          <div class="step_msg">
            <i class="iconfont icon-ic_exl"></i>
            <span class="step_msg_txt">上传失败（只支持excel文件）</span>
          </div>
          <div class="err_msg">
            <el-table :data="importErrList" maxHeight="150" :show-header="false" border>
              <el-table-column type="index" width="40" align="center"></el-table-column>
              <el-table-column show-overflow-tooltip>
                <template slot-scope="scope">{{scope.row}}</template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="analysis_err" v-if="analysisErrList.length">
          <div class="step_msg">
            <i class="iconfont icon-xiaoxitishi"></i>
            <span class="step_msg_txt">文件解析失败，请根据以下提示进行修改后再上传</span>
          </div>
          <div class="err_msg">
            <el-table :data="analysisErrList" :maxHeight="analysisHeight" :show-header="false" border>
              <el-table-column type="index" width="40" align="center"></el-table-column>
              <el-table-column show-overflow-tooltip>
                <template slot-scope="scope">{{scope.row}}</template>
              </el-table-column>
            </el-table>
          </div>
          <div class="err_file">
            <span @click="_down" class="err_file_btn">
              <i class="iconfont icon-btn_download"></i>下载错误文档
            </span>
            <span class="err_file_msg">查看更多信息，请下载错误文档</span>
          </div>
        </div>
      </div>
      <div class="step_seven" v-else-if="step === 7">
        <div class="center_msg">
          <i class="iconfont icon-zhengquetishi"></i>
          <span>模板导入成功</span>
        </div>
      </div>
      <span slot="footer" class="mes_btn">
      <el-button type="primary" v-if="step === 1" @click="importFile">导入</el-button>
      <el-button type="primary" v-if="step === 3" @click="reUpload">重新导入</el-button>
      <el-button type="primary" v-else-if="step === 5" @click="reAnalysis">重新解析</el-button>
      <el-button type="primary"
                 v-else-if="step === 6 || step === 7" @click="handleClose">确定</el-button>
      <el-button @click="handleClose" v-if="step !== 7 && step !== 6">取消</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ImportParam',
  data() {
    return {
      // 是否显示弹框
      dialogVisible: false,
      // 文件支持格式
      acceptFiles: ['.xls', '.xlsx'],
      // 当前步骤
      step: 1,
      // 文件密级
      secrecyGrade: this.defaultFileLevel,
      // 所选文件列表
      fileList: [],
      // 文件上传token
      importToken: null,
      // file服务器信息
      filesData: [],
      // 文件解析token
      analysisToken: null,
      // 上传失败列表
      importErrList: [],
      // 解析失败列表
      analysisErrList: [],
      // 任务号
      taskNumber: ''
    }
  },
  computed: {
    analysisHeight() {
      if (this.importErrList.length > 5) {
        return '150'
      } else {
        return (10 - this.importErrList.length) * 30 + ''
      }
    },
    fileSecretLevel() {
      return this.$store.state.dict.fileSecretLevel.labels || []
    }
  },
  methods: {
    // 打开方法
    openDialog(taskNumber) {
      this.step = 1
      this.taskNumber = taskNumber
      this.dialogVisible = true
    },
    // 超过文件限制数量
    handleExceed(files, fileList) {
      this.$message.error(`当前限制选择 10 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    // 添加文件回调
    fileChange(file, fileList) {
      if (/^(\.xls)|(xlsx)$/.test(file.name.slice(-4).toLowerCase())) {
        this.fileList.push(file)
      } else {
        fileList.pop()
      }
    },
    removeFile(file, fileList) {
      this.fileList = fileList
    },
    // 导入
    importFile() {
      if (!this.secrecyGrade) {
        this.$message({
          type: 'error',
          message: '请先选择文档密级',
          duration: 1500,
          center: true
        })
      } else if (!this.fileList.length) {
        this.$message({
          type: 'error',
          message: `请先选择后缀为${this.acceptFiles.join('、')}的文件`,
          duration: 1500,
          center: true
        })
      } else {
        this.filesData = []
        this.importErrList = []
        this.importToken = this.$axios.CancelToken.source()
        this.step = 2
        this.$refs.upload.submit()
      }
    },
    // 上传文件
    uploadFile(content) {
      let formdata = new FormData()
      formdata.append('file', content.file)
      formdata.append('fileSecretLevel', this.secrecyGrade)
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/uploadhistory/uploadHistory/upload',
        data: formdata,
        cancelToken: this.importToken.token,
        noCommit: true
      }).then(res => {
        this.filesData.push({
          fileName: res.data.fileName,
          path: res.data.filePath
        })
        if (this.filesData.length + this.importErrList.length === this.fileList.length) {
          // 所有文件上传完以后进行解析
          this.analysisFile()
        }
      }).catch(() => {
        this.importErrList.push(content.file.name)
        if (this.filesData.length + this.importErrList.length === this.fileList.length) {
          if (this.filesData.length) {
            // 所有文件上传完以后，且至少有一个上传成功，进行解析
            this.analysisFile()
          } else {
            // 否则上传失败
            this.step = 3
          }
        }
      })
    },
    // 解析文件
    analysisFile() {
      this.step = 4
      this.analysisToken = this.$axios.CancelToken.source()
      this.analysisErrList = []
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/workstagerecordtemplate/workstageRecordTemplate/importtemplate',
        data: {
          taskNumber: this.taskNumber,
          fileList: this.filesData
        },
        cancelToken: this.analysisToken.token,
        noCommit: true
      }).then(res => {
        if (!res.data.length && !this.importErrList.length) {
          // 全部文件解析成功，且上传成功，进入成功页面
          this.step = 7
        } else {
          // 否则进入错误信息页面
          this.analysisErrList = res.data || []
          this.step = 6
        }
      }).catch(() => {
        // 报错则解析失败
        this.step = 5
      })
    },
    // 重新上传
    reUpload() {
      this.clearData()
    },
    // 重新解析
    reAnalysis() {
      this.analysisFile()
    },
    // 下载错误文档
    _down() {
      if (this.analysisErrList.length) {
        this.$downloadErrorFile('参数模板错误信息.txt', this.analysisErrList.join('\r\n'))
      }
    },
    // 清空重置
    clearData() {
      this.step = 1
      this.secrecyGrade = this.defaultFileLevel
      this.importToken = null
      this.analysisToken = null
      this.fileList = []
      this.filesData = []
      this.importErrList = []
      this.analysisErrList = []
    },
    // 关闭弹框
    handleClose() {
      switch (this.step) {
        case 2:
          this.importToken.cancel('终止上传')
          this.step = 3
          break
        case 4:
          this.analysisToken.cancel('终止解析')
          break
        case 1:
        case 3:
        case 5:
          this.dialogVisible = false
          this.taskNumber = ''
          this.clearData()
          break
        case 6:
        case 7:
          this.dialogVisible = false
          this.taskNumber = ''
          this.clearData()
          this.$emit('refresh');
          break
      }
    }
  }
}
</script>

<style scoped lang="less">
  .import_param {
    .upload_btn {
      position: relative;
      overflow: hidden;
      margin-right: 10px;
      .file_btn {
        position: absolute;
        top: -20px;
        left: -20px;
        right: -20px;
        bottom: -20px;
        opacity: 0;
        cursor: pointer;
      }
    }
    .el-dialog__body {
      padding: 20px;
      .center_msg {
        padding: 20px 0;
        font-size: 14px;
        color: #333;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        .el-icon-loading {
          font-size: 30px;
          margin-right: 10px;
          color: #00b4ff;
        }
        .icon-tishi {
          padding-bottom: 2px;
          font-size: 20px;
          margin-right: 10px;
          color: #f8000f;
        }
        .icon-zhengquetishi {
          padding-bottom: 2px;
          font-size: 20px;
          margin-right: 10px;
          color: #33cc66;
        }
      }
      .step_six {
        .step_msg {
          color: @mesFontRed;
          font-size: 14px;
          margin-bottom: 20px;
          .icon-xiaoxitishi {
            font-size: 16px;
            margin-right: 3px;
          }
        }
        .err_file {
          display: flex;
          align-items: center;
          margin-top: 20px;
          .err_file_btn {
            flex: 0 0 130px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            color: #333;
            font-size: 14px;
            text-decoration: none;
            background-color: @mesBgWhite;
            border: @mesBorDefault;
            margin-right: 5px;
            cursor: pointer;
            .icon-btn_download {
              color: @mesIconDown;
              margin-right: 5px;
            }
          }
          .err_file_msg {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            color: @mesFontDefault;
            font-size: 14px;
          }
        }
      }
    }
  }
</style>
<style lang="less">
  .import_param {
    .step_six {
      .el-table td:first-child .cell {
        padding: 0 5px;
      }
    }
    .err_msg {
      margin-bottom: 20px;
      .el-table td {
        padding: 0;
        height: 30px;
        line-height: 30px;
      }
    }
  }
</style>
